package com.kelp.codetoolkit.utils

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import java.text.SimpleDateFormat

/**
 * @author: liuyuebai
 * @date: 2024/7/30 13:35
 * @description:
 */
object JSONUtil {

    private lateinit var objectMapper: ObjectMapper
    private val format: String = "yyyy-MM-dd HH:mm:ss"
    init {
        objectMapper = ObjectMapper()
        //禁止将日期序列成时间戳
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
        //禁止熟悉不存在时报错
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
        //允许字符串转换成数组
        objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
        //允许读取未知的枚举值转换成空
        objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
        //允许科学计数法
        objectMapper.enable(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS)
        objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)
        //序列化忽略空值
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
        //配置时间格式
        objectMapper.setDateFormat(SimpleDateFormat(format))
    }

    fun getInstance(): ObjectMapper {
        return objectMapper
    }

    /**
     * 将json字符串转换成java对象
     */
    fun <T> parse(obj:String,clazz: Class<T>): T {
        return objectMapper.readValue(obj,clazz)
    }

    /**
     * 将对像转成json字符串
     */
    fun toJSONString(obj:Any): String {
        return objectMapper.writeValueAsString(obj)
    }

    fun toFormatJSONString(obj:Any): String {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
    }
}